const log = require('../../util/log');
const config = require('../../util/config');

async function loginWechat(obj) {
	const {
		Network,
		Page,
		DOM,
		Runtime,
		Emulation
	} = this.client;
	obj = obj || {}
	obj.times = (obj.times || 0) + 1
	try {
		Page.navigate({
			url: 'https://wx.qq.com/'
		})
		return step1.call(this, obj)
	} catch (err) {
		log(err)
	}
}

async function step1(obj) {
	const {
		Network,
		Page,
		DOM,
		Runtime,
		Emulation
	} = this.client;
	obj.times++
	if (obj.times > config.chromeMaxTimes) {
		return new Promise((resolve, reject) => {
			reject('系统错误')
		})
	}
	try {
		var {
			result
		} = await Runtime.evaluate({
				expression: 'location.href'
			})
			if (result.value == 'https://wx2.qq.com/') {
				return new Promise(resolve => {
					resolve()
				})
			}
			return new Promise((resolve, reject) => {
				setTimeout(() => {
					step1.call(this, obj).then(result => {
						resolve(result)
					}, result => {
						reject(result)
					})
				}, 1000)
			})
	} catch (err) {
		log(err)
	}
}
